//
//  BaseNetwork.m
//  Matchmaker
//
//  Created by 高飞 on 15/8/27.
//  Copyright (c) 2015年 Changzhou. All rights reserved.
//

#import "BaseNetwork.h"
#import "AFNetworking.h"

@implementation BaseNetwork
static BaseNetwork *sharedObj = nil;
const char responseObjectKey;

+ (id)sharedNetwork {
    @synchronized (self)
    {
        if (sharedObj == nil)
        {
            sharedObj=[[self alloc] init];
        }
    }
    return sharedObj;
}

/**
 *  返回头文件数据
 *
 *  @return HttpHeader数据
 */
static inline NSDictionary *getHeaders(){
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    NSLog(@"getHeaders = %@",tempDic);
    return tempDic;
}

-(NSURLSessionConfiguration *)currentConfiguration
{
    _currentConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    [_currentConfiguration setHTTPCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    [_currentConfiguration setTimeoutIntervalForRequest:60];
    return _currentConfiguration;
}

-(void)currentConfiguratioWithAddNewHeaders:(NSDictionary *)addHeaders
{
    //增加新的addHeaders
    [self.currentConfiguration setHTTPAdditionalHeaders:addHeaders];
}

-(AFHTTPSessionManager *)sesstionManager
{
    _sesstionManager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:URL_ROOT] sessionConfiguration:_currentConfiguration];
    _sesstionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    _sesstionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    _sesstionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];

    return _sesstionManager;
}

/**
 *  <#Description#>
 *
 *  @param string            url 方法
 *  @param params            dic：数据内容
 *  @param completionHandler
 */
-(void)initWithMethodUrl:(NSString *)string
                  params:(id)params
             requestMode:(DGHTTPMethod)httpMethod
             loadingShow:(BOOL)show
            didFinshLoad:(void (^)(id result))completionHandler
{
    if(completionHandler != nil)
    {
        objc_setAssociatedObject(self, &responseObjectKey, completionHandler, OBJC_ASSOCIATION_COPY);
    }
    NSString *url = string;
    if (httpMethod == DGHTTPMethodGET) {
        [self loadWithGETObject:params andUrl:url loadingShow:show];
    }else{
        [self loadWithPOSTObject:params andUrl:url loadingShow:show];
    }
}

//POST
-(void)loadWithPOSTObject:(id)body
               andUrl:(NSString *)url
              loadingShow:(BOOL)show
{

    NSLog(@"%@,%@",url,body);

    [self currentConfiguratioWithAddNewHeaders:getHeaders()];

    [self.sesstionManager POST:url parameters:body progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


        [self responseSuccessedData:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [self responseFailData:error];
    }];
}

//GET
-(void)loadWithGETObject:(id)body
                  andUrl:(NSString *)url
             loadingShow:(BOOL)show
{

    NSLog(@"%@,%@",url,body);
    [self currentConfiguratioWithAddNewHeaders:getHeaders()];

    [self.sesstionManager GET:url parameters:body progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self responseSuccessedData:responseObject];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self responseFailData:error];
    }];
}

- (void)responseSuccessedData:(id)responseObject{
    
    if (responseObject) {
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"jsonData = %@",dataStr);
    }
    void (^theCompletionHandler)(id result) = objc_getAssociatedObject(self, &responseObjectKey);
    
    if(theCompletionHandler == nil)
        return;
    
    theCompletionHandler(responseObject);
}

- (void)responseFailData:(NSError *)error{
    NSLog(@"失败");
    [SVProgressHUD showInfoWithStatus:@"网络异常，稍后再试"];//错误提示
}

@end
